package day12;

import java.util.concurrent.locks.ReentrantLock;

//b.通过Lock锁编写三个线程 让其出现死锁的案例,
//提示: 添加3个对象  每个线程 分别锁两个对象 让
//其构成一个循环链  相互等待  可以参考 课上的案例
public class DeadLock{
    ReentrantLock l1=new ReentrantLock();
    ReentrantLock l2=new ReentrantLock();
    ReentrantLock l3=new ReentrantLock();
    public void one(){//l1->l3
        String name=Thread.currentThread().getName();
        l1.lock();
        System.out.println(name+"锁了l1等待l3");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        l3.lock();
        System.out.println(name+"锁了l1和l3");
        l3.unlock();
        System.out.println(name+"释放了l3");
        l1.unlock();
        System.out.println(name+"释放了l1");
    }
    public void two(){//l2->l1
        String name=Thread.currentThread().getName();
        l2.lock();
        System.out.println(name+"锁了l2等待l1");
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        l1.lock();
        System.out.println(name+"锁了l1和l2");
        l1.unlock();
        System.out.println(name+"释放了l1");
        l2.unlock();
        System.out.println(name+"释放了l2");
    }
    public void three(){//l3->l2
        String name=Thread.currentThread().getName();
        l3.lock();
        System.out.println(name+"锁了l3等待l2");
        l2.lock();
        System.out.println(name+"锁了l2和l3");
        l2.unlock();
        System.out.println(name+"释放了l2");
        l3.unlock();
        System.out.println(name+"释放了l3");
    }
    public static void main(String[] args) {
        DeadLock lock=new DeadLock();
        new Thread(()->{ lock.one();},"one").start();
        new Thread(()->{ lock.two();},"two").start();
        new Thread(()->{ lock.three();},"three").start();
    }
}
